#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    socket=new QTcpSocket(this);
    Ip=GetLolalHostIP();
    ui->comboBoxIp->addItem(Ip);

    connect(socket,&QTcpSocket::connected,this,[=](){

        ui->plainTextEdit_DispMsg->appendPlainText("**********已经连接到服务器端**********");
        ui->plainTextEdit_DispMsg->appendPlainText("**********peer address:"+ui->comboBoxIp->currentText());
        ui->plainTextEdit_DispMsg->appendPlainText("**********peer port:"+QString::number(ui->spinBoxPort->value()));
        ui->pushButton_Connect->setDisabled(true);
        ui->pushButton_Disconnect->setDisabled(false);

    });

    connect(socket,&QTcpSocket::disconnected,this,[=](){

        ui->pushButton_Connect->setDisabled(false);
        ui->pushButton_Disconnect->setDisabled(true);

    });

    connect(socket,&QTcpSocket::readyRead,this,[=](){
        while(socket->canReadLine())
        {
            ui->plainTextEdit_DispMsg->appendPlainText("[in]:"+QString(socket->readLine()));
        }
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}

QString MainWindow::GetLolalHostIP()
{
   QString str;
   QString Hostname=QHostInfo::localHostName();
   QHostInfo Ipname=QHostInfo::fromName(Hostname);
   QList<QHostAddress>list= Ipname.addresses();
   if(!list.empty())
   {
       for(QHostAddress ip:list)
       {
           if(ip.protocol()==QAbstractSocket::IPv4Protocol)
           {
               str=ip.toString();
               break;
           }
       }
   }
    return str;
}

//连接服务器
void MainWindow::on_pushButton_Connect_clicked()
{

    socket->connectToHost(QHostAddress(Ip),quint16(ui->spinBoxPort->value()));


}

//断开服务器
void MainWindow::on_pushButton_Disconnect_clicked()
{
    socket->close();
    ui->plainTextEdit_DispMsg->appendPlainText("**********已断开与服务器端的连接**********");
    ui->pushButton_Connect->setEnabled(true);
    ui->pushButton_Disconnect->setEnabled(false);


}

//发售那个信息

void MainWindow::on_pushButton_Send_clicked()
{
    QString text=ui->lineEdit_InputMsg->text();
    ui->plainTextEdit_DispMsg->appendPlainText("[out]:"+text);
    ui->lineEdit_InputMsg->clear();
    text.append("\n");
    QByteArray array=text.toUtf8();
    socket->write(array);


}
